<template>
	<!-- 购物车 -->
	<view class="container">
		<!-- 标题 -->
		<headTitle :title="title" :bottomline="true"></headTitle>
		<view class="cart-op">
			<text class="cart font28 color666" @tap="navToTabPage('/pages/coupon/productCoupon')">领劵</text>
			<text class="cart font28 color666" @tap="editOp" v-if="!showNone">{{ edit ? '完成' : '编辑' }}</text>
		</view>
		<view class="content bgfff" v-if="!showNone">
			<view class="item" v-for="(item,index) in shopList" :key="index">
				<view class="select" :class="{'active': item.flag, 'disable': item.goodsType}" @tap="check(index, item)">
					<image class="icon-active img-size-repeat" v-show="item.flag"></image>
				</view>
				<view class="photo" @tap="navToShop(item)">
					<view class="layer" v-if="item.goodsType"></view>
					<view class="txt font26 colorfff" v-if="item.goodsType === 1">已下架</view>
					<view class="txt font26 colorfff" v-if="item.goodsType === 2">缺货</view>
					<image :src="item.productPic " mode="aspectFill"></image>
				</view>
				<view class="info flex-column-between">
					<view class="info-top">
						<view class="show-two-text font28 color333"  @tap="navToShop(item)">{{item.productName }}</view>
						<view class="attr-border">
							<view class="attr flex-center" :class="{'disable': item.goodsType === 1}" @tap="openSku(item, index)">
								<view class="font22 color333">{{handleAttr(item)}}</view>
								<view class="attr-icon">
									<text class="yticon icon-you color333"></text>
								</view>
							</view>
						</view>
						<view class="num font20 color666" v-show="item.sku">{{handleSku(index, item)}}</view>
						<view class="down-prcie font20" v-if="item.price > item.presentPrice">{{handleMoney(item)}}</view>
						<view class="font20 color999" v-if="item.goodsType === 1">商品已下架</view>
					</view>
					<view class="info-bottom flex-center-between" v-if="item.goodsType !== 1">
						<view class="prcie fontb font24">
							¥<text>{{item.presentPrice}}</text>
						</view>
						<uni-number-box v-model="item.quantity" :min="1" :max="item.skuMun" @blurs='change(index)' @focus='numfocus' v-if="item.goodsType !== 2"></uni-number-box>
					</view>
				</view>
			</view>
			<uni-load-more :status="loadingType" class="hide"></uni-load-more>
		</view>
		<view class="bottom-none" v-if="!showNone"></view>
		
		<!-- 底部按钮 -->
		<view class="bottom flex-center-between bgfff" v-show="!showNone && showBottom">
			<view class="bottom-left flex-center" @tap="allcheck">
				<view class="select" :class="{'active': allChecked}">
					<image class="icon-active img-size-repeat" v-show="allChecked"></image>
				</view>
				<text class="font26 color666">全选</text>
			</view>
			<view class="bottom-right flex-center" v-show="!edit">
				<view class="flex-column">
					<view class="font28 color333">
						应付：
						<text class="font24 fontb red">¥</text>
						<text class="font36 fontb red">{{money}}</text>
					</view>
					<view class="font24 color999">不含邮费</view>
				</view>
				<button class="btn font28 colorfff" @tap="sumbitOrder">下单</button>
			</view>
			<view class="bottom-right flex-center" v-show="edit">
				<button class="btn-del font28 bgfff" @tap="removeOrdelete('remove')">移入收藏夹</button>
				<button class="btn-del font28 bgfff" @tap="removeOrdelete('del')">删除</button>
			</view>
		</view>
		
		<!-- 购物车为空 -->
		<view class="cart-empty flex-center-center" v-if="showNone">
			<view>
				<image src="/static/image/emptycart.png" mode=""></image>
				<view class="flex-center-center" @tap="navToTabPage('/pages/index/shopindex')">
					<text class="font30 color333">空空如也，赶紧去</text>
					<text class="font30 font-red">逛逛吧</text>
				</view>
			</view>
		</view>
		
		<!-- 规格选择 -->
		<selectSku ref="sku" :skuStockList="skuStockList" :productAttributeValueList="productAttributeValueList" optype="shopping"
			v-model='skuData' :id="shopid" :attrid="attrid" @shoppingok="affirm"></selectSku>
	</view>
</template>

<script>
import Api from '@/common/api'
import selectSku from "@/components/select-sku"
import headTitle from '@/components/head-title'
import uniLoadMore from '@/components/uni-load-more/uni-load-more'
import uniNumberBox from "@/components/uni-number-box/uni-number-box"
export default {
	data() {
		return {
			title: '购物车',
			pageNum: 1,
			loadingType: 'more', //加载更多状态
			shopList: [], // 购物车列表
			showNone: false, // 空的购物车
			countSelect: 0, // 可以选中的商品
			allChecked: false, // 全选反选
			money: 0, // 总价格
			selectArr: [], // 选中的数组
			edit: false, // 编辑按钮
			showBottom: true, // 显示底部
			skuStockList: [], // sku列表
			productAttributeValueList: [], // spu规格列表
			skuData: {}, // 规格数据
			shopid: 0, // 商品id
			attrid: 0, // 规格id
			idx: 0, // 选中规格的索引
			count: 0, // 购物车数量
			submitData: null, // 确认订单的数据
			params: {}, // 确认订单要提交订单
		}
	},
	//加载更多
	onReachBottom() {
		this.pageNum += 1
		this.getDate()
	},
	// 下拉刷新
	onPullDownRefresh() {
		this.pageNum = 1
		this.getDate('refresh')
		setTimeout(function () {
			uni.stopPullDownRefresh()
		}, 2000)
	},
	onLoad() {
		this.getDate('refresh')
		// 获取窗口可视高度
		let height = uni.getSystemInfoSync().windowHeight
		// 处理键盘弹出和收起
		uni.onWindowResize((res) => {
			if(height === res.size.windowHeight) {
				this.showBottom = true
			}
		})
	},
	methods: {
		// 下单
		async sumbitOrder() {
			if(!this.selectArr.length) {
				this.$api.msg('请选择商品')
				return 
			}
			
			this.params = {
				cartIds: this.selectArr.toString(),
				type: 2
			}
			let res = await Api.apiCall('get', Api.order.addOrder, this.params, true)
			if(res) {
				this.submitData = res
				// 页面跳转
				this.navToTabPage('/pages/order/createStoreOrder')
			}
		},
		// 移入收藏夹或删除商品
		async removeOrdelete(type) {
			if(!this.selectArr.length) {
				this.$api.msg('请选择商品')
				return 
			}
			
			if(type === 'del') {
				uni.showModal({
					content: '确定要删除吗？',
					cancelText: '我在想想',
					confirmText: '确定',
					success: (res) => {
						if (res.confirm) {
							this.remove()
						}
					}
				})
				return
			}else {
				let result = await Api.apiCall('get', Api.goods.removeCart, {
					id: this.selectArr.toString(),
				}, true)
				if(result) {
					this.handleShop()
				}
			}
			
		},
		// 操作移到收藏夹
		async remove() {
			let result = await Api.apiCall('get', Api.goods.delCart, {
				cart_id_list: this.selectArr.toString(),
			}, true)
			if(result) {
				this.handleShop()
			}
		},
		handleShop() {
			let arr = []
			this.selectArr.map(item => {
				this.shopList.some((val, index) => {
					if(item === val.id) {
						arr.push(index)
					}
				})
			})
			arr.sort().reverse().map(i => {
				this.shopList.splice(i, 1)
			})
			uni.showToast({
				title: '操作成功',
				icon: 'none'
			})
			if(this.shopList.length === 0) {
				this.showNone = true
			}
			this.count -= this.selectArr.length
			this.title = this.count === 0 ? '购物车' : `购物车(${this.count})`
			this.edit = false
			// 计算价格
			this.calculate()
		},
		// 选完规格确认按钮
		async affirm() {
			let shop = this.shopList[this.idx]
			//规格没修改到
			if(!this.skuData.id || this.skuData.id === shop.productSkuId) return 
			let res = await Api.apiCall('get', Api.goods.updateCartAttr, {
				id: this.shopList[this.idx].id,
				skuId: this.skuData.id,
			}, true)
			if(res) {
				// this.$set(this.shopList, this.idx, res)
				// 规格修改成功
				shop.productPic = this.skuData.pic
				shop.sp1 = this.skuData.sp1
				shop.sp2 = this.skuData.sp2
				shop.sp3 = this.skuData.sp3
				shop.skuMun = this.skuData.stock
				shop.productSkuId = this.skuData.id
				shop.price = this.skuData.price
				shop.presentPrice = this.skuData.price
				// 改为不缺货
				shop.goodsType = 0
				// 超过库存时，这里需要去请求修改购物车数量
				if(shop.quantity > shop.skuMun) {
					shop.quantity = shop.skuMun
					this.change(this.idx)
				}
			}
		},
		// 打开规格
		openSku(item, index){
			if(item.goodsType === 1) return 
			// 商品id
			this.shopid = item.productId
			// 规格id
			this.attrid = item.productSkuId
			// 打开规格
			this.$refs.sku.toggleSpec()
			
			this.idx = index
			// sku列表
			this.skuStockList = item.pmsSkuStockVoList || []
			// spu规格列表
			this.productAttributeValueList = item.productAttributeValueVoList || []
		},
		// 数字按钮得到焦点和失去焦点
		numfocus(flag) {
			this.showBottom = flag
		},
		// 处理规格展示
		handleAttr(item) {
			let str = ''
			if(item.sp1) {
				str += item.sp1 + ', '
			}
			if(item.sp2) {
				str += item.sp2 + ', '
			}
			if(item.sp3) {
				str += item.sp3 + ', '
			}
			if(str) {
				str = str.substring(0, str.length - 2)
			}
			return str
		},
		// 编辑按钮
		editOp() {
			this.edit = !this.edit
		},
		// 数量改变
		async change(index) {
			let res = await Api.apiCall('get', Api.goods.updateCartNum, { 
				id: this.shopList[index].id,
				quantity: this.shopList[index].quantity,
			}, true)
			if(res) {
				this.shopList[index].skuMun = res
			}else {
				this.shopList[index].quantity = 1
			}
			// 计算价格
			this.calculate()
		},
		// 计算总价格
		calculate() {
			this.money = 0
			this.shopList && this.shopList.map(item => {
				if(item.goodsType === 0 && item.flag) {
					this.money += parseFloat(item.quantity) * item.presentPrice
				}
			})
		},
		// 全选反选
		allcheck() {
			this.allChecked = !this.allChecked
			this.shopList && this.shopList.map(item => {
				if(item.goodsType === 0) {
					this.$set(item, 'flag', this.allChecked)
				}
			})
			if(this.allChecked) {
				this.selectArr = []
				this.shopList.map(item => {
					if(item.goodsType === 0) {
						this.selectArr.push(item.id)
					}
				})
			}else {
				this.selectArr = []
			}
			// 计算价格
			this.calculate()
		},
		// 跳转详情页
		navToShop(item) {
			if(item.goodsType === 1) {
				uni.navigateTo({ url: '/pages/cart/shopSoldOut' })
			}else {
				uni.navigateTo({ url: '/pages/product/product?id=' + item.productId })
			}
		},
		// 处理库存提示
		handleSku(idx, item) {
			if(item.goodsType) return 
			let str = ''
			item.pmsSkuStockVoList && item.pmsSkuStockVoList.some(val => {
				//规格id 
				if(val.id === item.productSkuId && val.lowStock >= val.stock) {
					this.$set(this.shopList[idx], 'sku', true)
					str = `仅剩${val.stock}件`
					return true
				}
			})
			return str
		},
		// 选中商品
		check(idx, item) {
			if(item.goodsType) return 
			let val = this.shopList[idx]
			let f = !val.flag
			this.$set(this.shopList[idx], 'flag', f)
			// 选中或取消选中
			f ?  this.selectArr.push(val.id) : this.selectArr.splice(this.shopList.indexOf(val.id), 1)
			// 设置全选或反选
			this.allChecked = this.selectArr.length === this.countSelect ? true : false
			// 计算价格
			this.calculate()
		},
		// 处理降价显示
		handleMoney(item){
			let str = ''
			if(item.price > item.presentPrice) {
				str = `比加入时降${item.price - item.presentPrice}元`
			}
			return str
		},
		// 页面跳转
		navToTabPage(url) {
			uni.navigateTo({ url })
		},
		/**
		 * 获取购物车列表
		 */
		async getDate(type = 'add'){
		    // 没有更多直接返回
			if (type === 'add') {
				if (this.loadingType === 'nomore') {
					return
				}
				this.loadingType = 'loading'
			} else {
				this.loadingType = 'more'
			}
			let list = await Api.apiCall('get', Api.goods.getShoppingCart, { 
				pageIndex: this.pageNum,
				pageSize: 50,
			}, true)
			if(!list) return 
			let shopList = list.cartItemList.recordList
			this.count = list.promoteAmount
			if(list.promoteAmount) {
				this.title = `购物车(${list.promoteAmount})`
			}
			if (type === 'refresh') {
				this.shopList = []
			}
			this.shopList = this.shopList.concat(shopList)
			// 购物车是空的
			this.shopList.length === 0 ? this.showNone = true : this.showNone = false
			
			this.selectArr = []
			// 可选中的数量
			this.countSelect = this.shopList.filter(item => {
				if(item.goodsType === 0) {
					// 如果全选选中后下拉加载的都需要选中
					if(this.allChecked) {
						this.$set(item, 'flag', true)
						this.selectArr.push(item.id)
					}
					return true
				}
			}).length
			// 计算价格
			this.calculate()
			// 判断是否有下一页数据
			this.loadingType = list.cartItemList.hasMore == 0 ? 'nomore' : 'more'
			if (type === 'refresh') {
				setTimeout(() => {
					uni.stopPullDownRefresh()
				}, 1000)
			}
		},
	},
	components: {
		headTitle,
		uniNumberBox,
		uniLoadMore,
		selectSku,
	}
}
</script>

<style lang="scss">
page {
	background-color: #F5F5F5;
}
page,
.container,
.cart-empty {
	height: 100%;
}

.cart-op {
	position: fixed;
	top: 0;
	right: 0;
	z-index: 10;
	height: 88rpx;
	line-height: 88rpx;
	.cart {
		width: 70rpx;
		height: 40rpx;
		line-height: 40rpx;
		text-align: center;
		margin-right: 30rpx;
		letter-spacing: 1rpx;
	}
}

.select {
	position: relative;
	margin-top: 83rpx;
	width: 42rpx;
	height: 42rpx;
	border-radius: 50%;
	border: 2rpx solid #DDD;
	&.disable {
		background-color: #F3F3F3;
	}
	&.active {
		border: 0;
	}
	.icon-active {
		position: absolute;
		top: 0;
		left: 0;
		width: 42rpx;
		height: 42rpx;
		background-image: url('/static/image/cartselect.png');
	}
}

.content {
	margin: 20rpx 0 0;
	padding-left: 30rpx;
	.item {
		display: flex;
		padding: 30rpx 30rpx 30rpx 0;
		width: 100%;
		min-height: 268rpx;
		&:not(:last-child) {
			border-bottom: 1rpx solid #EEE;
		}
		.photo {
			position: relative;
			width: 208rpx;
			height: 208rpx;
			margin: 0 20rpx;
			.layer {
				border-radius: 8rpx;
				position: absolute;
				top: 0;
				left: 0;
				right: 0;
				bottom: 0;
				z-index: 1;
				background: rgba(0, 0, 0, 0.2);
			}
			.txt {
				position: absolute;
				top: 50%;
				left: 50%;
				z-index: 2;
				transform: translate(-50%, -50%);
			}
			image {
				width: 100%;
				height: 100%;
				border-radius: 8rpx;
			}
		}
		.info {
			width: 400rpx;
			.info-top {
				&>view:not(:last-child) {
					margin-bottom: 16rpx;
				}
				.show-two-text {
					letter-spacing: 2.7rpx;
				}
				.attr-border {
					display: flex;
					.attr {
						line-height: 30rpx;
						padding: 7rpx 16rpx;
						background-color: #F5F5F5;
						border-radius: 8rpx;
						.attr-icon {
							margin-left: 15rpx;
							transform: rotate(90deg) scale(0.8);
							.icon-you {
								font-size: $font-base;
								color: #888;
							}
						}
						&.disable {
							view,
							text {
								color: #999;
							}
						}
					}
				}
				.num,
				.down-prcie {
					line-height: 28rpx;
					letter-spacing: 0.73rpx;
				}
				.down-prcie {
					color: #C53624;
				}
			}
			.info-bottom {
				margin-top: 30rpx;
				width: 400rpx;
				.prcie {
					color: #FF1701;
					line-height: 33rpx;
					letter-spacing: 1.1rpx;
					text {
						font-size: 32rpx;
					}
				}
				.uni-numbox {
					width: 180rpx;
					height: 46rpx;
					&/deep/.uni-numbox__minus,
					&/deep/.uni-numbox__value, 
					&/deep/.uni-numbox__plus {
						height: 46rpx;
						line-height: 46rpx;
					}
					&/deep/.uni-numbox__value {
						font-size: 28rpx;
					}
					&/deep/.uni-numbox__minus, 
					&/deep/.uni-numbox__plus {
						width: 50rpx;
					}
				}
			}
		}
	}
}

.hide {
	display: none;
}
.bottom-none {
	width: 100%;
	height: 132rpx;
}
.bottom {
	position: fixed;
	left: 0;
	bottom: 0;
	width: 100%;
	height: 112rpx;
	padding: 0 30rpx;
	border-top: 1rpx solid #ddd;
	z-index: 1;
	.bottom-left {
		.select {
			margin-top: 0;
			margin-right: 20rpx;
		}
	}
	.bottom-right {
		&>view {
			align-items: flex-end;
			margin-right: 24rpx;
			.red {
				color: #FF1701;
			}
		}
		.btn {
			width: 208rpx;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			border-radius: 40rpx;
			background-color: #C84739;
			&::after {
				border: 0;
			}
		}
		.btn-del {
			width: 186rpx;
			height: 70rpx;
			line-height: 70rpx;
			text-align: center;
			border: 1rpx solid #C84739;
			border-radius: 40rpx;
			margin-left: 30rpx;
			color: #C84739;
			padding: 0;
			&::after {
				border: 0;
			}
		}
	}
}

.cart-empty {
	margin-top: -88rpx;
	image {
		width: 374rpx;
		height: 288rpx;
		margin-bottom: 30rpx;
	}
	.font-red {
		color: #C84739;
	}
}
</style>
